package com.fansl.allround.wechat.mp.handler;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.fansl.allround.open.api.feign.RemoteJuHeService;
import com.fansl.allround.open.api.vo.NewsHeadlinesVO;
import com.fansl.allround.open.api.vo.WeatherVO;
import com.fansl.allround.wechat.mp.builder.TextBuilder;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.common.session.WxSessionManager;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutNewsMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author fansl
 * @Description: 消息时间处理
 * @date 2019/9/6 15:20
 */
@Slf4j
@Component
public class MsgHandler extends AbstractHandler {
    @Autowired
    private RemoteJuHeService juHeService;

    @Override
    public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage,
                                    Map<String, Object> context, WxMpService weixinService,
                                    WxSessionManager sessionManager) {

        if (!wxMessage.getMsgType().equals(WxConsts.XmlMsgType.EVENT)) {
            //TODO 可以选择将消息保存到本地
        }

        //当用户输入关键词如“你好”，“客服”等，并且有客服在线时，把消息转发给在线客服
        try {
            if (StrUtil.startWithAny(wxMessage.getContent(), "你好", "客服")
                    && weixinService.getKefuService().kfOnlineList()
                    .getKfOnlineList().size() > 0) {
                return WxMpXmlOutMessage.TRANSFER_CUSTOMER_SERVICE()
                        .fromUser(wxMessage.getToUser())
                        .toUser(wxMessage.getFromUser()).build();
            }
        } catch (WxErrorException e) {
            e.printStackTrace();
        }
        if(StrUtil.startWith(wxMessage.getContent().trim(),"天气")){
            String cityName = StrUtil.subAfter(wxMessage.getContent().trim(),"天气",true).trim();
           if(StrUtil.isNotBlank(cityName)){
                WeatherVO weatherVO =  juHeService.weather(cityName);
                StringBuffer sb = new StringBuffer();
                sb.append(weatherVO.getCity())
                      .append("\n")
                      .append("天气："+weatherVO.getRealtime().getInfo())
                      .append("\n")
                      .append("温度："+weatherVO.getRealtime().getTemperature()+",适度："+weatherVO.getRealtime().getHumidity())
                      .append("\n")
                      .append(weatherVO.getRealtime().getDirect()+":"+weatherVO.getRealtime().getPower())
                      .append("\n")
                      .append("空气质量指数："+weatherVO.getRealtime().getAqi())
                      .append("\n")
                      .append("未来几天的天气\n");
               weatherVO.getFuture().forEach(weatherFuture -> {
                   sb.append(weatherFuture.getDate())
                           .append("\n")
                           .append(weatherFuture.getWeather()+" "+weatherFuture.getTemperature())
                           .append("\n")
                           .append("白天："+weatherFuture.getWid().getDay()+" ")
                           .append("夜晚："+weatherFuture.getWid().getNight()+" ")
                           .append(weatherFuture.getDirect())
                           .append("\n");
               });
               return new TextBuilder().build(sb.toString(),wxMessage,weixinService);
           }
        }
        if(StrUtil.startWith(wxMessage.getContent().trim(),"新闻")){
            String newType = StrUtil.subAfter(wxMessage.getContent().trim(),"新闻",true).trim();
            if(StrUtil.isNotBlank(newType)){
                List<NewsHeadlinesVO> newsHeadlinesVOList =  juHeService.newsHeadlines(newType);
                List<WxMpXmlOutNewsMessage.Item> articles = new ArrayList();
                newsHeadlinesVOList.forEach(newsHeadlinesVO -> {
                    WxMpXmlOutNewsMessage.Item article = new WxMpXmlOutNewsMessage.Item();
                    article.setTitle(newsHeadlinesVO.getTitle());
                    article.setPicUrl(newsHeadlinesVO.getThumbnailPicList().get(0));
                    article.setUrl(newsHeadlinesVO.getUrl());
                    article.setDescription("来源："+newsHeadlinesVO.getAuthorName()+"\n新闻类型："+newsHeadlinesVO.getCategory());
                    articles.add(article);
                });

                return WxMpXmlOutNewsMessage.NEWS().addArticle(articles.get(RandomUtil.randomInt(articles.size())))
                        .fromUser(wxMessage.getToUser())
                        .toUser(wxMessage.getFromUser())
                        .build();
            }
        }
        if(wxMessage.getMsgType().equals(WxConsts.XmlMsgType.TEXT)){
            String content = wxMessage.getContent()
                    .replace("吗","")
                    .replace("你","我")
                    .replace("谁","小可爱")
                    .replace("?","!")
                    .replace("？","!");
            return new TextBuilder().build(content, wxMessage, weixinService);
        }
        //TODO 组装回复消息
        String content = "收到信息内容：" + JSONObject.toJSONString(wxMessage);

        return new TextBuilder().build(content, wxMessage, weixinService);

    }
}
